package com.collection.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


public class LLPayUtil {
	
	
	
	
	 public static String addSign(JSONObject reqObj, String rsa_private,
	            String md5_key){
		 
		 if (reqObj == null)
	        {
	            return "";
	        }
	        String sign_type = reqObj.getString("sign_type");
	        if ("MD5".equals(sign_type))
	        {
	            return addSignMD5(reqObj, md5_key);
	        } else
	        {
	            return "";
	        }
	 }
	
	
	
	 private static String addSignMD5(JSONObject reqObj, String md5_key)
	    {
	     
	        if (reqObj == null)
	        {
	            return "";
	        }
	        // 生成待签名串
	        String sign_src = genSignData(reqObj);
	        System.out.println("商户[" + reqObj.getString("oid_partner") + "]加签原串"
	                + sign_src);
	        sign_src += "&key=" + md5_key;
	        try
	        {
	            return Md5Algorithm.getInstance().md5Digest(
	                    sign_src.getBytes("utf-8"));
	        } catch (Exception e)
	        {
	            System.out.println("商户[" + reqObj.getString("oid_partner")
	                    + "]MD5加签名异常" + e.getMessage());
	            return "";
	        }
	    }
	 
	 
	 public static String genSignData(JSONObject jsonObject)
	    {
	        StringBuffer content = new StringBuffer();
	        

	        // 按照key做首字母升序排列
	        List<String> keys = new ArrayList<String>(jsonObject.keySet());
	        Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
	        for (int i = 0; i < keys.size(); i++)
	        {
	            String key = (String) keys.get(i);
	            if ("sign".equals(key))
	            {
	                continue;
	            }
	            String value = jsonObject.getString(key);
	            // 空串不参与签名
	            if (isnull(value))
	            {
	                continue;
	            }
	            content.append((i == 0 ? "" : "&") + key + "=" + value);

	        }
	        String signSrc = content.toString();
	        if (signSrc.startsWith("&"))
	        {
	            signSrc = signSrc.replaceFirst("&", "");
	        }
	        return signSrc;
	    }
	 
	 
	    public static boolean isnull(String str)
	    {
	        if (null == str || str.equalsIgnoreCase("null") || str.equals(""))
	        {
	            return true;
	        } else
	            return false;
	    }
	    /**
	     * 读取request流
	     * @param req
	     * @return
	     * @author guoyx
	     */
	    public static String readReqStr(HttpServletRequest request)
	    {
	        BufferedReader reader = null;
	        StringBuilder sb = new StringBuilder();
	        try
	        {
	            reader = new BufferedReader(new InputStreamReader(request
	                    .getInputStream(), "utf-8"));
	            String line = null;

	            while ((line = reader.readLine()) != null)
	            {
	                sb.append(line);
	            }
	        } catch (IOException e)
	        {
	            e.printStackTrace();
	        } finally
	        {
	            try
	            {
	                if (null != reader)
	                {
	                    reader.close();
	                }
	            } catch (IOException e)
	            {

	            }
	        }
	        return sb.toString();
	    }
	    /**
	     * 签名验证
	     * 
	     * @param reqStr
	     * @return
	     */
	    public static boolean checkSign(String reqStr, String rsa_public, String md5_key)
	    {
	        JSONObject reqObj = JSON.parseObject(reqStr);
	        if (reqObj == null)
	        {
	            return false;
	        }
	        String sign_type = reqObj.getString("sign_type");
	        if ("MD5".equals(sign_type))
	        {
	            return checkSignMD5(reqObj, md5_key);
	        }else {
				return false;
			}
	    }
	    /**
	     * MD5签名验证
	     * 
	     * @param signSrc
	     * @param sign
	     * @return
	     * @author guoyx
	     */
	    private static boolean checkSignMD5(JSONObject reqObj, String md5_key)
	    {
	        if (reqObj == null)
	        {
	            return false;
	        }
	        String sign = reqObj.getString("sign");
	        // 生成待签名串
	        String sign_src = genSignData(reqObj);
	        sign_src += "&key=" + md5_key;
	        try
	        {
	            if (sign.equals(Md5Algorithm.getInstance().md5Digest(
	                    sign_src.getBytes("utf-8"))))
	            {
	                System.out.println("商户[" + reqObj.getString("oid_partner")
	                        + "]MD5签名验证通过");
	                return true;
	            } else
	            {
	                return false;
	            }
	        } catch (UnsupportedEncodingException e)
	        {
	            return false;
	        }
	    }
	   

}
